package com.chinacoal.microservice.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.mapper.CcmsSmartleasingHouseTypeMapper;
import com.chinacoal.microservice.mapper.CcmsSmartleasingRoomMapper;
import com.chinacoal.microservice.pojo.CcmsSmartleasingHouseType;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.service.HouseTypeManagementService;
import com.chinacoal.microservice.util.CodeMsg;
import com.chinacoal.microservice.util.QueryCriteria;
import com.chinacoal.microservice.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author zhuliang
 * @version V1.0
 * @Description: 房源管理-户型管理-实现类
 * @date 2020-11-11 11：25
 */
@Slf4j
@Service
public class HouseTypeManagementServiceImpl implements HouseTypeManagementService {

    @Autowired
    private CcmsSmartleasingHouseTypeMapper houseTypeMapper;

    @Autowired
    private CcmsSmartleasingRoomMapper roomMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @Description: 查询所有的户型信息（带分页）
     * @author zhuliang
     * @date 2020/11/11 11:29
     */
    @Override
    public Result<List<CcmsSmartleasingHouseType>> getAllTypes(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页查询条件
        Page<CcmsSmartleasingHouseType> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页查询
        List<CcmsSmartleasingHouseType> houseTypes = houseTypeMapper.getAllByPage(toPage, currency.getProperty(), currency.getManagementOffice());

        //将多字段的数据，进行拆分返回
        if (houseTypes != null) {
            for (CcmsSmartleasingHouseType houseType : houseTypes) {
                if (StringUtils.isNotEmpty(houseType.getSupportingFacilities())) {
                    String[] splitSupportingFacilities = houseType.getSupportingFacilities().split(",");
                    houseType.setSupportingFacilitiesList(splitSupportingFacilities);
                }
                if (StringUtils.isNotEmpty(houseType.getApartmentRenderings())) {
                    String[] splitApartmentRenderings = houseType.getApartmentRenderings().split(",");
                    houseType.setApartmentRenderingsList(splitApartmentRenderings);
                }
            }
        }

        return Result.success(houseTypes, toPage.getTotal());
    }

    /**
     * @Description: 根据户型id查询对应的户型信息
     * @author zhuliang
     * @date 2020/11/11 11:58
     */
    @Override
    public Result<CcmsSmartleasingHouseType> getTypeById(String pkHouseTypeId, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //根据户型id查询户型信息
        CcmsSmartleasingHouseType houseType = houseTypeMapper.getHouseTypeById(pkHouseTypeId, currency.getProperty(), currency.getManagementOffice());

        //将多字段的数据，进行拆分写入
        if (houseType != null) {
            if (StringUtils.isNotEmpty(houseType.getSupportingFacilities())) {
                String[] splitSupportingFacilities = houseType.getSupportingFacilities().split(",");
                houseType.setSupportingFacilitiesList(splitSupportingFacilities);
            }
            if (StringUtils.isNotEmpty(houseType.getApartmentRenderings())) {
                String[] splitApartmentRenderings = houseType.getApartmentRenderings().split(",");
                houseType.setApartmentRenderingsList(splitApartmentRenderings);
            }
        } else {
            log.error(CodeMsg.NOT_FOUND.toString() + "-->此户型信息无权限访问，或数据丢失-->" + pkHouseTypeId);
            return Result.error(CodeMsg.NOT_FOUND);
        }

        return Result.success(houseType);
    }

    /**
     * @Description: 添加户型信息
     * @author zhuliang
     * @date 2020/11/11 13:45
     */
    @Override
    public Result addHouseType(CcmsSmartleasingHouseType houseType, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //完善户型信息
        houseType.setPkHouseTypeId(UUID.randomUUID() + "");
        houseType.setCreationDate(new Date());
        houseType.setLastUpdateDate(new Date());
        houseType.setCreatedBy(currency.getLoginId());
        houseType.setLastUpdatedBy(currency.getLoginId());

        //添加户型信息
        houseTypeMapper.insert(houseType);

        return Result.success();
    }

    /**
     * @Description: 修改户型信息
     * @author zhuliang
     * @date 2020/11/11 13:57
     */
    @Override
    public Result updateHouseType(CcmsSmartleasingHouseType houseType, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //判断这个户型是否有房间引用
        if (!houseType.getFkBuildingId().equals(houseType.getOldFkBuildingId())) {
            String id = roomMapper.getCountByHouseTypeId(houseType.getFkBuildingId());
            if (StringUtils.isNotBlank(id)) {
                log.error(CodeMsg.HOUSE_TYPE_UPDATE_BUILDING.toString() + "-->户型id:" + houseType.getPkHouseTypeId());
                return Result.error(CodeMsg.HOUSE_TYPE_UPDATE_BUILDING);
            }
        }

        //修改最后修改时间
        houseType.setLastUpdateDate(new Date());
        houseType.setLastUpdatedBy(currency.getLoginId());

        //根据户型信息的id修改户型信息
        houseTypeMapper.updateById(houseType);

        return Result.success();
    }

    /**
     * @Description: 根据户型id删除户型信息
     * @author zhuliang
     * @date 2020/11/11 14:03
     */
    @Override
    public Result deleteHouseType(String deleteId, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //判断是否还有关联的房间
        String byHouseTypeId = roomMapper.getCountByHouseTypeId(deleteId);
        if (StringUtils.isNotBlank(byHouseTypeId)) {
            log.error(CodeMsg.DATA_HAS_BEEN_USED.toString() + "-->户型id:" + deleteId);
            return Result.error(CodeMsg.DATA_HAS_BEEN_USED);
        }

        //批量修改户型信息
        houseTypeMapper.updateToDeleteById("1",
                                            new Date(),
                                            deleteId,
                                            currency.getLoginId(),
                                            currency.getProperty(),
                                            currency.getManagementOffice());

        return Result.success();
    }

    /**
     * @Description: 条件查询（带分页）
     * @author zhuliang
     * @date 2020/11/11 14:52
     */
    @Override
    public Result<List<CcmsSmartleasingHouseType>> getConditionQuery(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页查询条件
        Page<CcmsSmartleasingHouseType> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页查询
        List<CcmsSmartleasingHouseType> houseTypeList = houseTypeMapper.getAllByCondition(queryCriteria.getFkRoomTypeId(),
                                                                                            queryCriteria.getInputString(),
                                                                                            queryCriteria.getProvinceId(),
                                                                                            queryCriteria.getCityId(),
                                                                                            queryCriteria.getAreaId(),
                                                                                            queryCriteria.getFkBuildingId(),
                                                                                            currency.getProperty(),
                                                                                            currency.getManagementOffice(),
                                                                                            toPage);

        //将多字段的数据，进行拆分返回
        if (houseTypeList != null) {
            for (CcmsSmartleasingHouseType houseType : houseTypeList) {
                if (StringUtils.isNotEmpty(houseType.getSupportingFacilities())) {
                    String[] splitSupportingFacilities = houseType.getSupportingFacilities().split(",");
                    houseType.setSupportingFacilitiesList(splitSupportingFacilities);
                }
                if (StringUtils.isNotEmpty(houseType.getApartmentRenderings())) {
                    String[] splitApartmentRenderings = houseType.getApartmentRenderings().split(",");
                    houseType.setApartmentRenderingsList(splitApartmentRenderings);
                }
            }
        }

        return Result.success(houseTypeList, toPage.getTotal());
    }

    /**
     * @Description: 根据楼宇id查询户型信息
     * @author zhuliang
     * @date 2020/11/12 17:28
     */
    @Override
    public Result<List<CcmsSmartleasingHouseType>> getHouseTypeByBuildingId(String fkBuildingId, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //查询对应的户型信息
        List<CcmsSmartleasingHouseType> houseTypes = houseTypeMapper.getAllByBuildingId(fkBuildingId, currency.getProperty(), currency.getManagementOffice());

        //将多字段的数据，进行拆分返回
        if (houseTypes != null) {
            for (CcmsSmartleasingHouseType houseType : houseTypes) {
                if (StringUtils.isNotEmpty(houseType.getSupportingFacilities())) {
                    String[] splitSupportingFacilities = houseType.getSupportingFacilities().split(",");
                    houseType.setSupportingFacilitiesList(splitSupportingFacilities);
                }
                if (StringUtils.isNotEmpty(houseType.getApartmentRenderings())) {
                    String[] splitApartmentRenderings = houseType.getApartmentRenderings().split(",");
                    houseType.setApartmentRenderingsList(splitApartmentRenderings);
                }
            }
        }

        return Result.success(houseTypes);
    }
}
